<!-- 素材中心 -->
<template>
    <view class="centerPage" :style="{ '--color': color }">
        <status-bar title="素材中心" :goHome="fromShare"></status-bar>
        <view class="classNav bgwhite" :style="{ top: totalHeight + 'px' }">
            <u-tabs
                :list="tabList"
                :current="current"
                keyName="website_list_title"
                :lineColor="color"
                lineWidth="32"
                @click="tabClick"
                :inactiveStyle="{ color: '#777', fontSize: '32rpx', transform: 'scale(1)' }"
                itemStyle="height: 50px;"
                :activeStyle="{ color: '#444', fontSize: '32rpx', fontWeight: 'bold', transform: 'scale(1.05)' }"
            ></u-tabs>
        </view>
        <view class="p-top100" v-if="list.length">
            <view class="item padding40-30 p-re" v-for="(item, index) in list" :key="index">
                <view class="d-flex">
                    <u-avatar :src="$imgUrls(item.v_headimg)" size="40"></u-avatar>
                    <view class="p-left20 flex-1">
                        <view>
                            <view class="d-flex j-sb a-center m-bot10">
                                <view class="size30 color_11 bold">{{ item.v_name }}</view>
                                <view class="d-flex" @click="handleTip(item, true)">
                                    <text class="iconfont icon-gantanhao-xianxingyuankuang size36 color_99"></text>
                                    <text class="size26 color_99 m-left10">免责声明</text>
                                </view>
                            </view>
                            <view class="h6 color_66">{{ item.website_article_addtime }}</view>
                        </view>
                        <view @click="toUrl('/pages/goods/goods_detail?goodsid=' + item.website_article_id)" class="size28 color_11 p-right30 p-top20">{{ item.website_article_info }}</view>
                        <!-- 一张大图 -->
                        <image
                            :src="$imgUrls(item.website_article_atlas[0])"
                            mode="widthFix"
                            class="large m-top20 m-bot10"
                            v-if="item.website_article_atlas.length == 1"
                            @click="previewImg(item.website_article_atlas, 0)"
                        ></image>
                        <!-- 多张缩略 -->
                        <view class="d-flex f-wrap m-top20 m-bot10" v-if="item.website_article_atlas.length > 1">
                            <image
                                :src="$imgUrls(itm)"
                                mode="aspectFill"
                                class="thumb m-right4 m-bot4"
                                v-for="(itm, idx) in item.website_article_atlas"
                                :key="idx"
                                @click="previewImg(item.website_article_atlas, idx)"
                            ></image>
                        </view>
                        <view class="d-flex p-top20">
                            <view class="d-flex m-right60" @click="selectPoster(item)" v-if="item.website_article_atlas.length">
                                <text class="iconfont icon-tupian size34 color_99"></text>
                                <text class="m-left10 h6 color_11">生成海报</text>
                            </view>
                            <view class="d-flex m-right60" @click="handleCopy(item)">
                                <text class="iconfont icon-fuzhi size34 color_99"></text>
                                <text class="m-left10 h6 color_11">复制素材</text>
                            </view>
                            <view class="d-flex p-re" @click="shareItem = item">
                                <text class="iconfont icon-002 size34 color_99"></text>
                                <text class="m-left10 h6 color_11">分享给好友</text>
                                <!-- 点击share分享按钮时会触发onShareAppMessage -->
                                <button open-type="share" class="btn-contact"></button>
                            </view>
                        </view>
                    </view>
                </view>
                <!-- 免责声明 -->
                <view class="tip p-ab padding20" v-if="item.showTip">
                    <text class="size26 line40">素材均来自互联网，如有侵权请联系客服删除！</text>
                    <text class="iconfont icon-guanbi1 size26 color_66 p-ab" @click="handleTip(item, false)"></text>
                </view>
            </view>
        </view>

        <empty v-else cat="3" msg="您还没有相关的素材" pad="300"></empty>

        <view class="btns d-flex">
            <view class="first flex-1 flexac">
                <text class="iconfont icon-duosucai size36 white"></text>
                <text class="size28 white m-left20">素材库</text>
            </view>
            <view class="last flex-1 flexac bgwhite" @click="$rectTo('/privatePage/material/sharePoster')">
                <text class="iconfont icon-tupian size36"></text>
                <text class="size28 m-left20">分享海报</text>
            </view>
        </view>

        <u-popup :show="showPopup" :round="10" closeable @close="showPopup = false">
            <view>
                <view class="size28 color_33 text-center p-top30 p-bot30">点击图片，生成海报</view>
                <swiper indicator-dots class="swiper">
                    <swiper-item class="text-center" v-for="(item, index) in posterItem.website_article_atlas" :key="index" @click="getPoster(item)">
                        <image :src="$imgUrls(item)" mode="heightFix" class="img"></image>
                    </swiper-item>
                </swiper>
            </view>
        </u-popup>

        <canvas :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }" canvas-id="firstCanvas" id="firstCanvas" style="position: fixed; top: -9999px"></canvas>

        <u-overlay :show="showOverlay" @click="showOverlay = false">
            <view class="overlay height flexac f-column" @tap.stop>
                <image :src="posterImg" mode="widthFix" show-menu-by-longpress class="viewbox5 m-bot30"></image>
                <u-icon name="close-circle" size="30" color="#fff" label="长按保存或直接分享" labelPos="bottom" labelSize="13" labelColor="#fff" space="6" @click="showOverlay = false"></u-icon>
            </view>
        </u-overlay>

        <view class="iconfont icon-zengjia size80 thmeColor" @click="toUrl('/privatePage/material/addMaterial')" v-if="operator == 1"></view>
    </view>
</template>

<script>
    import { mapState } from 'vuex';
    export default {
        data() {
            return {
                fromShare: 0,
                tabList: [],
                current: 0,
                list: [],
                shareItem: {},
                showPopup: false,
                posterItem: {},
                canvasWidth: 0,
                canvasHeight: 0,
                showOverlay: false,
                posterImg: '',
                operator: 0, // 有无添加素材的权限
                page: 1,
                pagecount: 5,
                getMore: true,
                website_list_id: ''
            };
        },
        computed: {
            ...mapState(['totalHeight', 'color', 'vid', 'share'])
        },
        onLoad(e) {
            if (e.fromShare) this.fromShare = e.fromShare;
        },
        onShow() {
            this.getCate();
        },
        methods: {
            getCate() {
                this.$http
                    .get({
                        url: '/PrivateSphereApi/getResource',
                        data: {
                            type: 'material'
                        }
                    })
                    .then((res) => {
                        if (res.code != 200) return this.$Toast(res.msg);
                        const result = res.data || [];
                        this.tabList = result;

                        this.website_list_id = this.tabList[this.current].website_list_id;
                        this.getList();
                        this.operator = res.operator;
                    });
            },
            getList() {
                this.$http
                    .get({
                        url: '/PrivateSphereApi/getResource',
                        data: {
                            type: 'material',
                            website_list_id: this.website_list_id,
                            page: this.page,
                            pagecount: this.pagecount
                        }
                    })
                    .then((res) => {
                        if (res.code != 200) return this.$Toast(res.msg);
                        const result = res.data || [];
                        this.page == 1 ? (this.list = result) : (this.list = [...this.list, ...result]);
                        if (result.length < this.pagecount) this.getMore = false;
                    });
            },
            tabClick({ index, website_list_id }) {
                this.current = index;
                this.page = 1;
                this.getMore = true;
                this.$pop.pageScrollTo();
                this.website_list_id = website_list_id;
                this.getList();
            },
            handleTip(item, bool) {
                this.$set(item, 'showTip', bool);
            },
            previewImg(atlas, idx) {
                let urls = atlas.map((item) => this.$imgUrls(item));
                uni.previewImage({
                    current: idx, // 链接或索引值
                    urls,
                    indicator: 'number'
                });
            },
            getImgInfo(src) {
                // 获取图片信息
                return new Promise((resolve) => {
                    uni.getImageInfo({
                        src,
                        success(res) {
                            resolve(res);
                        }
                    });
                });
            },
            getLocalPath(url) {
                // 下载到本地返回临时路径
                return new Promise((resolve) => {
                    uni.downloadFile({
                        url,
                        success(res) {
                            resolve(res.tempFilePath);
                        }
                    });
                });
            },
            getQr(website_article_id) {
                return new Promise((resolve) => {
                    this.$http
                        .get({
                            url: '/PrivateSphereApi/getArticleQr',
                            data: {
                                website_article_id
                            }
                        })
                        .then((res) => {
                            resolve(res);
                        });
                });
            },
            breakTextLines(ctx, text, maxWidth) {
                // 文本换行
                let words = text.split('');
                let line = '';
                let lines = [];
                for (let i = 0; i < words.length; i++) {
                    line = line + words[i];
                    let metrics = ctx.measureText(line);
                    if (metrics.width >= maxWidth) {
                        lines.push(line);
                        line = '';
                    }
                }
                if (line) lines.push(line);
                return lines;
            },
            imgBaseUrl(img) {
                const reg = /^(http|https)/;
                if (!img) return;
                if (img.search(reg) != -1) return img;
                return this.baseUrl + img;
            },
            selectPoster(item) {
                this.posterItem = item;
                if (item.website_article_atlas.length > 1) {
                    this.showPopup = true;
                    return;
                }
                this.getPoster(item.website_article_atlas[0]);
            },
            async getPoster(poster) {
                let that = this;
                that.showPopup = false;
                that.$showLoading('海报生成中...');
                let ctx = uni.createCanvasContext('firstCanvas');
                // 背景
                let { path, width, height } = await that.getImgInfo(that.imgBaseUrl(poster));
                that.canvasWidth = 750;
                that.canvasHeight = (750 / width) * height + 180;
                ctx.drawImage(path, 0, 0, 750, (750 / width) * height); // 位置宽高
                // 矩形
                ctx.fillStyle = '#FFFFFF';
                ctx.rect(0, (750 / width) * height, 750, 180);
                ctx.fill();
                // 头像
                ctx.save();
                ctx.beginPath();
                ctx.arc(80, (750 / width) * height + 90, 50, 0, 2 * Math.PI);
                ctx.clip();
                let avatar = await that.getLocalPath(that.imgBaseUrl(that.posterItem.v_headimg));
                ctx.drawImage(avatar, 30, (750 / width) * height + 40, 100, 100);
                ctx.restore();
                // 文本（bug：y应算文本左下角）
                ctx.setFontSize(28);
                ctx.setFillStyle('#000');
                ctx.fillText(that.posterItem.v_name, 160, (750 / width) * height + 68);
                ctx.setFontSize(24);
                ctx.setFillStyle('#999');
                let lines = that.breakTextLines(ctx, that.share.desc, 300);
                lines.forEach((line, index) => {
                    if (index < 2) ctx.fillText(line, 160, (750 / width) * height + 88 + (index + 1) * 28);
                });
                // 二维码
                let res = await that.getQr(that.posterItem.website_article_id);
                if (res.code != 200) return that.$Toast(res.msg);
                let code = await that.getLocalPath(that.imgBaseUrl(res.data));
                ctx.drawImage(code, 560, (750 / width) * height + 10, 160, 160);

                ctx.draw(false, () => {
                    // 绘制完成后回调
                    setTimeout(() => {
                        uni.canvasToTempFilePath({
                            // 当前画布内容导出生成图片
                            canvasId: 'firstCanvas',
                            success(res) {
                                console.log(res.tempFilePath, 'res.tempFilePath');
                                that.posterImg = res.tempFilePath;
                                that.showOverlay = true;
                            },
                            complete() {
                                that.$hideLoading();
                            }
                        });
                    }, 100);
                });
            },
            getAuth(atlas) {
                let that = this;
                uni.getSetting({
                    success(res) {
                        // 获取用户授权结果
                        if (!res.authSetting['scope.writePhotosAlbum']) {
                            uni.authorize({
                                scope: 'scope.writePhotosAlbum',
                                success() {
                                    that.savePoster(atlas);
                                }
                            });
                        } else {
                            // 已授权保存到相册
                            that.savePoster(atlas);
                        }
                    }
                });
            },
            handleCopy(item) {
                this.$pop.setClip(item.website_article_info);
                if (!item.website_article_atlas) return;
                this.getAuth(item.website_article_atlas);
            },
            savePoster(atlas) {
                let that = this;
                let count = 0;
                for (let i = 0; i < atlas.length; i++) {
                    uni.downloadFile({
                        url: that.imgBaseUrl(atlas[i]),
                        success(res) {
                            uni.saveImageToPhotosAlbum({
                                // 保存图片到相册
                                filePath: res.tempFilePath,
                                success() {
                                    count = count + 1;
                                    if ((count = atlas.length)) that.$Toast('请到手机相册查看图片素材');
                                }
                            });
                        }
                    });
                }
            }
        },
        onReachBottom() {
            if (!this.getMore) return;
            this.page++;
            this.getList();
        },
        onShareAppMessage(res) {
            if (res.from == 'button') {
                // 页面内分享按钮
                return {
                    title: this.shareItem.website_article_info,
                    path: `/pages/index/index?share_v_id=${this.vid}&pageType=10&gid=${this.shareItem.website_article_id}&w=2&pid=${this.vid}`
                };
            } else if (res.from == 'menu') {
                // 右上角分享按钮
                return {
                    title: '素材中心',
                    path: `/pages/index/index?share_v_id=${this.vid}&pageType=13&w=2&pid=${this.vid}`
                };
            }
        }
    };
</script>

<style lang="scss" scoped>
    .centerPage {
        padding-bottom: calc(100rpx + constant(safe-area-inset-bottom));
        padding-bottom: calc(100rpx + env(safe-area-inset-bottom));
    }
    .classNav {
        position: fixed;
        left: 0;
        // right: 0; // 解决右侧遮挡
        z-index: 20;
        width: 100%;
    }
    .item {
        border-bottom: 1rpx solid #d9d9d9;
        .large {
            width: 360rpx;
        }
        .thumb {
            width: 180rpx;
            height: 180rpx;
        }
        .related {
            height: 120rpx;
            box-shadow: 1rpx 2rpx 9rpx 1rpx rgba(56, 56, 56, 0.15);
            padding: 18rpx;
            .img {
                width: 84rpx;
                height: 84rpx;
            }
        }
        .tip {
            width: 328rpx;
            background: #eef7ff;
            filter: drop-shadow(-4rpx 0rpx 9rpx rgba(60, 60, 60, 0.16));
            border-radius: 2rpx;
            color: #8b9eb0;
            top: 100rpx;
            right: 18rpx;
            z-index: 10;
            &::after {
                content: '';
                width: 0;
                height: 0;
                border-bottom: 30rpx solid #eef7ff;
                border-left: 30rpx solid transparent;
                position: absolute;
                top: -30rpx;
                left: 50%;
                margin-left: -15rpx;
            }
            .icon-guanbi1 {
                top: 2rpx;
                right: 2rpx;
            }
        }
    }
    .btns {
        position: fixed;
        left: 0;
        bottom: constant(safe-area-inset-bottom);
        bottom: env(safe-area-inset-bottom);
        width: 100%;
        height: 90rpx;
        z-index: 20;
        .first {
            background: #65a3ff;
            border-radius: 16rpx 0rpx 0rpx 0rpx;
        }
        .last {
            border: 1px solid #65a3ff;
            border-radius: 0rpx 16rpx 0rpx 0rpx;
            color: #65a3ff;
        }
    }
    .swiper {
        height: 480rpx;
        .img {
            height: 420rpx;
        }
    }
    .overlay {
        overflow-y: auto;
        padding-bottom: constant(safe-area-inset-bottom);
        padding-bottom: env(safe-area-inset-bottom);
    }
    .icon-zengjia {
        position: fixed;
        right: 20rpx;
        bottom: 250rpx;
        z-index: 20;
    }
</style>
